package com.cn.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

public class BaiduTranslateUtil {

    // 百度翻译 API 的 AppID 和 密钥
    private static final String APP_ID = "20220601001236328";
    private static final String SECURITY_KEY = "lYQ6l080xUJex9eCt3Ul";
    private static final String URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    public static void main(String[] args) {
        //String query = "你好!我想要去英国留学";
        String query = "59 Franklyn Avenue";
        String translatedText = translateChineseToEnglish(query);
        System.out.println("翻译结果: " + translatedText);
    }

    /**
     * 中文翻译为英文
     * @param query
     * @return
     */
    public static String translateChineseToEnglish(String query){
        String from = "zh"; // 源语言: 中文
        String to = "en";   // 目标语言: 英文
        String jsonResponse = translateToJson(query, from, to);
        String translatedText = extractTranslation(jsonResponse);
        return translatedText;
    }

    /**
     * 中文翻译为英文
     * @param query
     * @return
     */
    public static String translateEnglishToChinese(String query){
        String from = "en"; // 源语言: 中文
        String to = "zh";   // 目标语言: 英文
        String jsonResponse = translateToJson(query, from, to);
        String translatedText = extractTranslation(jsonResponse);
        return translatedText;
    }


    // 发送翻译请求
    public static String translateToJson(String query, String from, String to) {
        try {
            String salt = String.valueOf(System.currentTimeMillis());
            String sign = md5(APP_ID + query + salt + SECURITY_KEY);

            Map<String, String> params = new HashMap<>();
            params.put("q", URLEncoder.encode(query, "UTF-8"));
            params.put("from", from);
            params.put("to", to);
            params.put("appid", APP_ID);
            params.put("salt", salt);
            params.put("sign", sign);

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }

            String queryString = sb.substring(0, sb.length() - 1);
            URL url = new URL(URL + "?" + queryString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return response.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 使用 Jackson 解析 JSON，提取 dst 字段
    public static String extractTranslation(String jsonResponse) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(jsonResponse);
            JsonNode transResultNode = rootNode.path("trans_result");

            if (transResultNode.isArray() && transResultNode.size() > 0) {
                JsonNode firstTranslationNode = transResultNode.get(0);
                return firstTranslationNode.path("dst").asText();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 生成 MD5 签名
    private static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}